<template>
  <view class="container">
    <uni-nav-bar
      dark
      :fixed="true"
      shadow
      background-color="#007AFF"
      status-bar
      left-icon="left"
      left-text="返回"
      title="添加设备"
      @clickLeft="back"
    />
    <view class="content">
      <uni-forms
        ref="baseForm"
        :modelValue="formData"
        label-width="180rpx"
        label-align="right"
        :rules="rules"
      >
        <uni-forms-item label="设备图片" required name="picUrl">
          <uni-file-picker
            limit="1"
            title="选择1张图片"
            ref="files"
            :auto-upload="false"
            :image-styles="imageStyles"
            v-model="dataFile"
            fileType="image"
            @select="onFileSelect"
            @delete="onFileDelete"
          >
          </uni-file-picker>
        </uni-forms-item>
        <uni-forms-item label="设备名称" required name="deviceName">
          <uni-easyinput
            v-model="formData.deviceName"
            placeholder="请输入设备名称"
          />
        </uni-forms-item>
        <uni-forms-item label="设备分组" required name="groupId">
          <uni-data-select
            v-model="formData.groupId"
            :localdata="groupList"
            @change="change"
            placeholder="请选择设备分组"
            style="height: 30rpx !important"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="设备类型" required name="deviceType">
          <uni-data-select
            v-model="formData.deviceType"
            :localdata="getSelectList('mqtt_device_type')"
            @change="change"
            placeholder="请选择设备类型"
            style="height: 30rpx !important"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="联网方式" required name="networkType">
          <uni-data-select
            v-model="formData.networkType"
            :localdata="getSelectList('mqtt_device_networktype')"
            @change="change"
            placeholder="请选择联网方式"
            style="height: 30rpx !important"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="选择MQTT" required name="mqttConfigId">
          <uni-data-select
            v-model="formData.mqttConfigId"
            :localdata="mqttList"
            @change="change"
            placeholder="选择MQTT"
            style="height: 30rpx !important"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="设备地址" required name="address">
          <view class="address-input-container">
            <uni-easyinput
              v-model="formData.address"
              placeholder="请输入设备地址"
             readonly="true"
            />
            <uni-icons
              type="location"
              size="20"
              color="#007AFF"
              class="address-icon"
              @click="openMapPicker"
            />
          </view>
        </uni-forms-item>

        <uni-forms-item label="网关SN编号"  required name="gatewayId">
          <uni-easyinput
            v-model="formData.gatewayId"
            placeholder="请输入网关SN编号"
          />
        </uni-forms-item>

        <uni-forms-item label="设备唯一标识符" required name="deviceKey">
          <view class="device-key-container">
            <uni-easyinput
              v-model="formData.deviceKey"
              placeholder="设备唯一标识符"
         
            />
            <button 
              v-if="!formData.deviceKey" 
              @click="generateDeviceKey" 
              class="generate-btn"
              type="default"
              size="mini"
            >
              生成
            </button>
          </view>
        </uni-forms-item>

        <uni-forms-item label="设备编号" name="serialNumber">
          <uni-easyinput
            v-model="formData.serialNumber"
            placeholder="请输入设备序列号"
          />
        </uni-forms-item>

        <uni-forms-item label="设备固件编号" name="firmwareId">
          <uni-easyinput
            v-model="formData.firmwareId"
            placeholder="请输入设备的固件编号"
          />
        </uni-forms-item>

        <uni-forms-item label="报警状态" required name="alarmStatus">
          <uni-data-select
            v-model="formData.alarmStatus"
            :localdata="getSelectList('mqtt_config_enabled')"
            @change="change"
            placeholder="请选择报警状态"
            style="height: 30rpx !important"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="默认报警" required name="alarmDefult">
          <uni-data-select
            v-model="formData.alarmDefult"
            :localdata="getSelectList('mqtt_config_enabled')"
            @change="change"
            placeholder="请选择默认报警"
            style="height: 30rpx !important"
          ></uni-data-select>
        </uni-forms-item>

        <uni-forms-item label="备注"  name="nickname">
          <uni-easyinput v-model="formData.nickname" placeholder="请输入备注" />
        </uni-forms-item>

        <button @click="submitForm">上传文件</button>
      </uni-forms>
    </view>

    <!-- 地图选择器 - 使用固定定位覆盖整个页面 -->
    <view v-if="showMap" class="map-fullscreen" @touchmove.stop.prevent>
    
      <view class="map-header">
        <view class="search-container">
          <view class="search-box">
            <view class="search-input-wrapper">
              <input
                class="search-input"
                v-model="searchKeyword"
                placeholder="搜索地点"
                @input="onSearchInput"
                confirm-type="search"
              />
              <view class="search-btn" @tap="searchPlaces">
                <uni-icons type="search" size="18" color="#FFFFFF"></uni-icons>
              </view>
            </view>
          </view>
        </view>

        <!-- 搜索结果列表 -->
        <view v-if="searchResults.length > 0" class="search-results">
          <scroll-view scroll-y class="search-results-scroll">
            <view
              v-for="(item, index) in searchResults"
              :key="index"
              class="result-item"
              @tap="selectSearchResult(item)"
            >
              <view class="result-title">{{ item.title }}</view>
              <view class="result-address">{{ item.address }}</view>
            </view>
          </scroll-view>
        </view>
      </view>

      <map-picker
        :initialLatitude="mapData.latitude"
        :initialLongitude="mapData.longitude"
        @locationChanged="onLocationChanged"
      />

      <view class="map-footer">
        <view class="map-btn confirm-btn" @tap="confirmLocation">确认位置</view>
        <view class="map-btn cancel-btn" @tap="cancelMap">取消</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { getSelectList } from '@/utils/wxdict'
import { ref, onMounted, watch } from "vue";
import MapPicker from '../components/map-picker.vue';
import { onLoad } from "@dcloudio/uni-app";
import { useMemberStore } from "@/stores";
import { config } from "@/config";
const back = () => {
  uni.navigateBack({ delta: 1 });
};
const baseURL = config.baseUrl + config.baseApi;
const userStore = useMemberStore();

// 组件引用
const baseForm = ref<any>(null);

const imageStyles = ref({
  width: 120,
  height: 120,
  border: {
    color: "#ff5a5f",
    width: 2,
    style: "dashed",
    radius: "2px",
  },
});
const dataFile = ref([]);

// 地图相关数据
const showMap = ref(false);
const searchKeyword = ref('');
const searchResults = ref<any[]>([]);
const mapData = ref({
  latitude: 39.909,
  longitude: 116.397,
});
const searchDebounceTimer = ref<number | null>(null);

// 监听搜索关键词变化
watch(searchKeyword, (newValue) => {
  if (newValue.trim()) {
    // 使用防抖处理，避免频繁请求
    if (searchDebounceTimer.value) {
      clearTimeout(searchDebounceTimer.value);
    }
    searchDebounceTimer.value = setTimeout(() => {
      searchPlaces();
    }, 500) as unknown as number;
  } else {
    searchResults.value = [];
  }
});

// 搜索输入事件
const onSearchInput = () => {
  // 监听函数中已经处理了搜索逻辑
};

// 搜索地点
const searchPlaces = () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = [];
    return;
  }

  uni.showLoading({ title: '搜索中...' });

  uni.request({
    url: 'https://apis.map.qq.com/ws/place/v1/search',
    data: {
      keyword: searchKeyword.value,
      boundary: `nearby(${mapData.value.latitude},${mapData.value.longitude},1000)`,
      key: '72QBZ-BWA6B-RMHU2-N5T3U-YG3BE-K3FIU',
      page_size: 10
    },
    success: (res: any) => {
      if (res.data.status === 0) {
        searchResults.value = res.data.data;
      } else {
        uni.showToast({
          title: '搜索失败: ' + res.data.message,
          icon: 'none'
        });
      }
    },
    fail: () => {
      uni.showToast({
        title: '搜索请求失败',
        icon: 'none'
      });
    },
    complete: () => {
      uni.hideLoading();
    }
  });
};

// 选择搜索结果
const selectSearchResult = (item: any) => {
  mapData.value.latitude = item.location.lat;
  mapData.value.longitude = item.location.lng;
  formData.value.address = item.address;
  searchResults.value = []; // 清空搜索结果列表
  searchKeyword.value = ''; // 清空搜索关键词

  // 保存经纬度
  formData.value.latitude = item.location.lat;
  formData.value.longitude = item.location.lng;
};

// 处理地图位置变更
const onLocationChanged = (location: { latitude: number, longitude: number }) => {
  mapData.value.latitude = location.latitude;
  mapData.value.longitude = location.longitude;

  // 根据经纬度获取地址信息
  getAddressFromLocation(location.latitude, location.longitude);
};

const formData = ref({
  // id: undefined,
  deviceKey: undefined,
  mqttConfigId: undefined,
  // mqttClientId: "",
  deviceName: "",
  deviceType: undefined,
  gatewayId: undefined,
  networkType: "",
  // signalStrength: "",
  state: 0,
  address: "",
  serialNumber: "",
  firmwareId: "",
  picUrl: "",
  areaId: undefined,
  longitude: 0,
  latitude: 0,
  nickname: "",
  groupId: undefined,
  alarmStatus: "1",
  alarmDefult: "0",
  // productId: undefined,
  // productKey: undefined,
  onlineTime: undefined,
  offlineTime: undefined,
  activeTime: undefined,
  ip: undefined,
  deviceSecret: undefined,
  mqttUsername: undefined,
  mqttPassword: undefined,
  authType: undefined,
  config: undefined
});

const value = ref("");
const deviceTypeList = ref([
  { value: "0", text: "EG设备" },
  { value: "1", text: "GM设备" },
]);

const mqttList = ref([
  { value: "1", text: "服务器1" },
  { value: "2", text: "服务器2" },
]);

const groupList = ref([
  { value: 1, text: "默认分组" },
  { value: 2, text: "测试分组" },
]);

// 生成设备唯一标识符
const generateDeviceKey = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  let uuid = ''
  for (let i = 0; i < 12; i++) {
    uuid += chars[Math.floor(Math.random() * chars.length)]
  }
  formData.value.deviceKey = uuid
  uni.showToast({
    title: '设备标识符已生成',
    icon: 'success'
  })
};

// 打开地图选择器
const openMapPicker = () => {
  // 获取当前位置作为默认位置
  uni.getLocation({
    type: "gcj02",
    success: (res) => {
      mapData.value.latitude = res.latitude;
      mapData.value.longitude = res.longitude;
      showMap.value = true;
    },
    fail: () => {
      // 如果获取位置失败，使用默认位置
      showMap.value = true;
    },
  });
};

// 根据经纬度获取地址
const getAddressFromLocation = (latitude: number, longitude: number) => {
  uni.request({
    url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=72QBZ-BWA6B-RMHU2-N5T3U-YG3BE-K3FIU`,
    success: (res: any) => {
      if (res.data.status === 0) {
        const address = res.data.result.formatted_addresses.recommend;
        formData.value.address = address;
      }
    },
    fail: () => {
      // 如果获取地址失败，使用经纬度作为地址
      formData.value.address = `${latitude.toFixed(6)}, ${longitude.toFixed(
        6
      )}`;
    },
  });
};

// 确认位置
const confirmLocation = () => {
  formData.value.latitude = mapData.value.latitude;
  formData.value.longitude = mapData.value.longitude;
  showMap.value = false;
  uni.showToast({
    title: "位置已保存",
    icon: "success",
  });
};

// 取消地图选择
const cancelMap = () => {
  showMap.value = false;
};

// 文件选择事件
const onFileSelect = (event: any) => {
  console.log("文件选择:", event.tempFiles);
  if (event.tempFiles.length > 0) {
    const tempFilePath = event.tempFiles[0].path;
    formData.value.picUrl = tempFilePath;
    //upload(tempFilePath);
  }
};

// 文件删除事件
const onFileDelete = () => {
  console.log("文件已删除");
};
const change = (e: any) => {
  console.log(e);
};

// 上传文件到服务器
const upload = async (tempFilePath: string) => {
  console.log(JSON.stringify(formData.value));
  try {
    // 执行上传
    const uploadResult = await uni.uploadFile({
      url: baseURL + "/mqtt/device/uploadMini", // 替换为实际的上传接口
      filePath: tempFilePath,
      name: "file",
      formData: formData.value,
      header: {
        Authorization: `Bearer ${userStore.accessToken}`,
        ContentType: "application/x-www-form-urlencoded",
      },
    });
    console.log("上传结果:", uploadResult);
  } catch (error: any) {
    console.error("文件上传失败:", error);
    uni.showToast({
      title: '上传失败，请重试',
      icon: 'none'
    });
  }
};

// 使用清理后的数据上传文件到服务器
const uploadWithCleanData = async (tempFilePath: string, cleanData: any) => {
  console.log("清理后的表单数据:", JSON.stringify(cleanData));
  try {
    // 执行上传
    const uploadResult = await uni.uploadFile({
      url: baseURL + "/mqtt/device/uploadMini", // 替换为实际的上传接口
      filePath: tempFilePath,
      name: "file",
      formData: cleanData,
      header: {
        Authorization: `Bearer ${userStore.accessToken}`,
        ContentType: "application/x-www-form-urlencoded",
      },
    });
    console.log("上传结果:", uploadResult);
    
    // 处理上传成功的响应
    if (uploadResult.statusCode === 200) {
        uni.showToast({
          title: '设备添加成功',
          icon: 'success'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } else {
        uni.showToast({
          title: uploadResult.data.message || '添加失败',
          icon: 'none'
        });
      }
      
  } catch (error: any) {
    console.error("文件上传失败:", error);
    uni.showToast({
      title: '上传失败，请重试',
      icon: 'none'
    });
  }
};

// 表单验证规则
const rules = ref({
  deviceName: {
    rules: [
      { required: true, errorMessage: "设备名称不能为空" },
      {
        minLength: 2,
        maxLength: 50,
        errorMessage: "设备名称长度应在2到50个字符之间",
      },
    ],
  },
  groupId: {
    rules: [{ required: true, errorMessage: "请选择设备分组" }],
  },
  deviceType: {
    rules: [{ required: true, errorMessage: "设备类型不能为空" }],
  },
  networkType: {
    rules: [{ required: true, errorMessage: "请选择联网方式" }],
  },
  mqttConfigId: {
    rules: [{ required: true, errorMessage: "请选择MQTT服务器" }],
  },
  deviceKey: {
    rules: [{ required: true, errorMessage: "设备唯一标识符不能为空" }],
  },
  gatewayId: {

    rules: [
       { required: true, errorMessage: "SN不能为空" },
      {
        minLength: 5,
        maxLength: 20,
        errorMessage: "网关SN编号长度应在5到20个字符之间",
      },
    ],
  },
  address: {
    rules: [{ required: true, errorMessage: "设备地址不能为空" }],
  },
  alarmStatus: {
    rules: [{ required: true, errorMessage: "请选择报警状态" }],
  },
  alarmDefult: {
    rules: [{ required: true, errorMessage: "请选择默认报警" }],
  },
});

// 提交表单
const submitForm = async () => {
  if (!baseForm.value) return;
  
  try {
    const isValidatePass = await baseForm.value.validate();
    if (!isValidatePass) {
      return;
    }
  } catch (error) {
    console.log('表单验证失败:', error);
    return;
  }
  
  // 清理 undefined 值，避免后端解析错误
  const cleanFormData = Object.fromEntries(
    Object.entries(formData.value).filter(([key, value]) => value !== undefined && value !== null && value !== '')
  );
  
  try {
    uni.showLoading({ title: '提交中...' });
    
    // 处理文件上传
    if (formData.value.picUrl && formData.value.picUrl.length > 0) {
      await uploadWithCleanData(formData.value.picUrl, cleanFormData);
    } else {
      // 如果没有图片，直接提交表单数据
      const { addDevice } = await import('@/pagesS1/api/deviceinfo');
      const result = await addDevice(cleanFormData);
      
      if (result.success || result.code === 200) {
        uni.showToast({
          title: '设备添加成功',
          icon: 'success'
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } else {
        uni.showToast({
          title: result.message || '添加失败',
          icon: 'none'
        });
      }
    }
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({
      title: '提交失败，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};
</script>

<style lang="scss" scoped>
.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
}

.address-input-container {
  display: flex;
  align-items: center;
  width: 100%;

  .address-icon {
    margin-left: 10rpx;
    padding: 10rpx;
    cursor: pointer;
  }
}

.device-key-container {
  display: flex;
  align-items: center;
  width: 100%;
  
  .generate-btn {
    margin-left: 10rpx;
    padding: 10rpx 20rpx;
    background-color: #007AFF;
    color: white;
    border: none;
    border-radius: 4rpx;
    font-size: 24rpx;
  }
}
.content {
  margin: 20rpx;

/* 全屏地图容器 */
.map-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.map-header {
  padding: 20rpx;
  // padding-top: calc(var(--status-bar-height, 20px) + 20rpx);
  z-index: 10;
}

.search-container {
  width: 100%;
}

.search-box {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8rpx;
  padding: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.search-input-wrapper {
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: transparent;
}

.search-btn {
  width: 70rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #007aff;
  border-radius: 8rpx;
}

.search-results {
  margin-top: 10rpx;
  max-height: 400rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 9;
}

.search-results-scroll {
  max-height: 400rpx;
}

.result-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.result-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.result-address {
  font-size: 24rpx;
  color: #999;
}

.map-footer {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
}
  .map-container {
    width: 100%;
    height: 400rpx;
    margin: 20rpx 0;
    border-radius: 10rpx;
    overflow: hidden;
    .map-controls {
      position: absolute;
      bottom: 20rpx;
      left: 20rpx;
      right: 20rpx;
      display: flex;
      justify-content: space-between;

      .map-btn {
        padding: 20rpx 40rpx;
        border-radius: 10rpx;
        color: white;
        font-size: 28rpx;
        text-align: center;
      }

      .confirm-btn {
        background-color: #007aff;
      }

      .cancel-btn {
        background-color: #999;
      }
    }

  }



}

::v-deep .uni-forms-item {
  position: relative;
  display: flex;
  margin-bottom: 25rpx !important;
  flex-direction: row;
}



.button {
  display: flex;
  align-items: center;
  height: 35px;
  margin-left: 10px;
}


/* 覆盖层样式（脱离 .content 限制，确保全屏覆盖） */
.map-fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
  background-color: #fff;
  display: flex;
  flex-direction: column;
}

.map-header {
  padding: 20rpx;
  z-index: 10;
}

.search-container {
  width: 100%;
}

.search-box {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 8rpx;
  padding: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.search-input-wrapper {
  display: flex;
  align-items: center;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: transparent;
}

.search-btn {
  width: 70rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #007aff;
  border-radius: 8rpx;
}

.search-results {
  margin-top: 10rpx;
  max-height: 400rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 9;
}

.search-results-scroll {
  max-height: 400rpx;
}

.result-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.result-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 6rpx;
}

.result-address {
  font-size: 24rpx;
  color: #999;
}

.map-footer {
  padding: 20rpx;
  display: flex;
  justify-content: space-between;
}

/* 底部按钮样式（用于 map-footer） */
.map-btn {
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
  color: #fff;
  font-size: 28rpx;
  text-align: center;
}

.confirm-btn {
  background-color: #007aff;
}

.cancel-btn {
  background-color: #999;
}
/* 顶部搜索组件在全屏地图下的安全区域与下移间距（响应式） */
.map-fullscreen .map-header {
  /* 基础下移，适配不同密度屏幕使用 rpx */
  margin-top: 130rpx;
  /* iOS 11 旧版 WebKit/微信：安全区常量语法 */
  padding-top: calc(constant(safe-area-inset-top) + 32rpx);
  /* 标准语法：大多数现代环境 */
  padding-top: calc(env(safe-area-inset-top) + 32rpx);
}
</style>
